package cool.webstudy.singletondynamicscheduler.utils.scheduler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import cool.webstudy.singletondynamicscheduler.constant.enums.EnabledStatusFlagEnum;
import cool.webstudy.singletondynamicscheduler.mapper.scheduler.SchedulerTaskRecordMapper;
import cool.webstudy.singletondynamicscheduler.model.po.scheduler.SchedulerTaskRecordPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author think
 * @date 2025/2/20 13:11
 * @description: 在spring boot项目启动完成后加载并执行数据库中启用状态的定时任务
 */
@Service
public class InitSchedulerConfigRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(InitSchedulerConfigRunner.class);

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;
    @Autowired
    private SchedulerTaskRecordMapper schedulerTaskRecordMapper;

    @Override
    public void run(String... args) {
        // 初始加载数据库里状态为启用的定时任务
        LambdaQueryWrapper<SchedulerTaskRecordPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SchedulerTaskRecordPO::getTaskStatus, EnabledStatusFlagEnum.ENABLED.getFlag());
        try {
            List<SchedulerTaskRecordPO> existedEnabledTaskList = schedulerTaskRecordMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(existedEnabledTaskList)) {
                for (SchedulerTaskRecordPO schedulerTaskRecordPO : existedEnabledTaskList) {
                    SchedulerRunnable task = new SchedulerRunnable(schedulerTaskRecordPO.getUnCode(),schedulerTaskRecordPO.getBeanName(), schedulerTaskRecordPO.getMethodName(), schedulerTaskRecordPO.getMethodParams());
                    cronTaskRegistrar.addCronTask(task, schedulerTaskRecordPO.getCronExpression());
                }
                logger.info("定时任务已加载完毕...");
            }
        } catch (Exception e) {
            logger.error("加载定时任务出错：{}", e.getMessage());
        }
    }
}
